package de.idgard.android.addon.ui.dialogs;

import android.app.Dialog;
import android.content.Context;
import android.view.View;
import android.view.Window;
import android.webkit.WebView;
import android.widget.CheckBox;
import android.widget.EditText;
import de.idgard.android.R;
import de.idgard.android.addon.services.GlobalServiceRegistry;
import de.idgard.android.addon.ui.services.WebIconService;
import de.idgard.android.addon.ui.services.impl.UIServiceRegistry;
import de.idgard.webapp.shared.dto.bookmark.BookmarkLinkDto;

/**
 * @author PRATIK - IDGARD bookmark dialog.
 * 
 */
public class IDGardSaveBookmarkDialog extends Dialog {

	private WebView currentWebView;

	private EditText etBookmarkName;
	private CheckBox cbShowInPortal;

	public IDGardSaveBookmarkDialog(Context context, WebView currentWebView) {
		super(context);
		this.currentWebView = currentWebView;
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.idgard_dialog_save_bookmark);

		buildGui();
	}

	public void buildGui() {
		etBookmarkName = (EditText) findViewById(R.id.et_bookmarkName);
		etBookmarkName.setText(currentWebView.getTitle() != null ? currentWebView.getTitle() : "");

		cbShowInPortal = (CheckBox) findViewById(R.id.cb_showin_portal);

		findViewById(R.id.btn_cancel_bookmark).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				dismiss();
			}
		});
		findViewById(R.id.btn_save_bookmark).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				saveBookmarkToServer();
				dismiss();
			}
		});
	}

	private BookmarkLinkDto buildBookmarkPayload() {
		BookmarkLinkDto bookmark = new BookmarkLinkDto();
		bookmark.setName(etBookmarkName.getText().toString());
		bookmark.setLink(currentWebView.getUrl());
		bookmark.setDescription("");
		bookmark.setShowInPortal(cbShowInPortal.isChecked());
		bookmark.setIcon(getWebIconService().getFaviconAsBase64());

		return bookmark;
	}

	private WebIconService getWebIconService() {
		return UIServiceRegistry.instance().getWebIconService();
	}

	private void saveBookmarkToServer() {
		GlobalServiceRegistry.instance().getBackendService().saveBookmark(buildBookmarkPayload()).fire();
	}

}
